import { useRequest } from 'ahooks'
import { getQuestionListService } from '../../../services/question'
import { useSearchParams } from 'react-router-dom'
import {
  LIST_SEARCH_PARAM_KEY,
  LIST_PAGE_PARAM_KEY,
  LIST_PAGE_SIZE_PARAM_KEY,
  LIST_PAGE_SIZE,
} from '../../../constants'
import { ResDataType } from '../../../services/types'
import { OptionType } from './types'

export default function useLoadQuestionListData({ isStar, isDeleted }: Partial<OptionType> = {}): ResDataType {
  const [searchParams] = useSearchParams()

  const { data, loading, error, refresh } = useRequest(
    async function () {
      const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
      const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '') || 1
      const pageSize = parseInt(searchParams.get(LIST_PAGE_SIZE_PARAM_KEY) || '') || LIST_PAGE_SIZE

      return await getQuestionListService({ keyword, isStar, isDeleted, page, pageSize })
    },
    {
      refreshDeps: [searchParams],
    }
  )

  return { data, loading, error, refresh }
}
